package com.zzb.weixin.model.msg.basic;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.zzb.weixin.constant.Constant.WXMsgType;
import com.zzb.weixin.json.JsonObject;

/**
 * 抽象消息类 提供各种消息类型字段、头部消息对象以及写入和读取抽象方法
 * 
 * @author zzb
 * */
public abstract class Msg {
	
	protected Document document;
	public Msg() {
	}
	public Msg(Document document) {
		this.document = document;
		this.head = new HeadMsg(document);
		read();
	}
	/** 消息头 */
	protected HeadMsg head;

	/**
	 * 写入消息内容
	 * 
	 * @param document
	 */
	public abstract Element write();

	/**
	 * 读取消息内容
	 * 
	 * @param document
	 */
	public abstract void read();

	/**
	 * 获取节点文本内容
	 * 
	 * @param document
	 *            文档
	 * @param element
	 *            节点名称
	 * @return 内容
	 */
	protected String getElementContent(String element) {
		if (getDocument().getElementsByTagName(element).getLength() > 0) {// 判断是否有节点
			return getDocument().getElementsByTagName(element).item(0)
					.getTextContent();
		} else {
			return null;
		}
	}
	
	/**
	 * 转换为客服消息结构
	 */
	public abstract JsonObject toJson();

	public HeadMsg getHead() {
		return head;
	}

	public void setHead(HeadMsg head) {
		this.head = head;
	}

	public String getToUserName() {
		return head.getToUserName();
	}

	public void setToUserName(String toUserName) {
		head.setToUserName(toUserName);
	}

	public String getFromUserName() {
		return head.getFromUserName();
	}

	public void setFromUserName(String fromUserName) {
		head.setFromUserName(fromUserName);
	}

	public Long getCreateTime() {
		return head.getCreateTime();
	}

	public void setCreateTime(Long createTime) {
		head.setCreateTime(createTime);
	}

	public WXMsgType getMsgType() {
		return head.getMsgType();
	}

	public void setMsgType(WXMsgType msgType) {
		head.setMsgType(msgType);
	}

	public Document getDocument() {
		return document;
	}
	/**
	 * 设置xml消息内容并解析
	 * @param document
	 */
	public void setDocument(Document document) {
		this.document = document;
		if(this.head!=null)this.head.setDocument(document);
	}
}
